package com.xiashitech.apiservice.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.xiashitech.apiservice.config.AuthConfig;
import com.xiashitech.apiservice.service.IUserInfoService;
import com.xiashitech.interfaces.apiservice.dto.user.UserInfoRequest;
import com.xiashitech.interfaces.apiservice.dto.user.UserInfoResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor(onConstructor =@_(@Autowired))
public class UserInfoServiceImpl implements IUserInfoService {

    private final AuthConfig authConfig;

    @Override
    public UserInfoResponse retrieveUserInfo(UserInfoRequest userRequest) {
        Map<String,Object> params = new HashMap();
        params.put("id",userRequest.getId());
        params.put("lookup_field","username");
        params.put("bk_app_code",authConfig.getUserForAppCode());
        params.put("bk_app_secret",authConfig.getUserForAppSecret());
        params.put("bk_username",authConfig.getUserForUsername());
        HttpResponse httpResponse = HttpRequest.post(authConfig.getUserForUrl())
                .body(JSONUtil.toJsonStr(params), "application/json;charset=UTF-8")
                .timeout(30 * 1000)
                .execute();
        if(httpResponse.isOk() && JSONUtil.isTypeJSON(httpResponse.body())) {
            UserInfoResponse userResponse = JSONUtil.toBean(httpResponse.body(), UserInfoResponse.class);
            return userResponse;
        } else {
            return null;
        }
    }
}
